package tt.dz.service.imp.middleware;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import tt.dz.entity.exception.BizException;
import tt.dz.service.imp.middleware.instruction.Ev3c2Instructions;
import tt.dz.service.imp.middleware.notify.app.NotifyAppServer;
import tt.dz.service.imp.middleware.vo.settings.SettingBody;
import tt.dz.tcp.rpc.as.client.constant.AppServerConstant;
import tt.dz.tcp.socket.LongConnectionSendMsgImpl;
import tt.dz.tcp.socket.MessageFuture;
import tt.dz.tcp.socket.exception.CreateConnectionFailException;
import tt.dz.tcp.socket.exception.DuplicateInstructionException;
import tt.dz.tcp.socket.exception.RetryFailException;
import tt.dz.util.serialGenerater;

import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by luoyp on 2016/6/17.
 * 1.x协议电桩参数查询服务
 */
@Service
public class QueryServiceV1
{
	private Log log = LogFactory.getLog(QueryServiceV1.class);

	@Value("${charger.settings.retrieve.timeout.sec}")
	private int Retrieve_Timeout;//查询超时时间

	@Autowired
	LongConnectionSendMsgImpl longConnection;

	/**
	 * 发送查询指令, 返回电桩的回复报文, 该过程是一个同步过程
	 * @param chargerId 桩号
	 * @return 电桩回复的报文
	 * @throws CreateConnectionFailException
	 * @throws RetryFailException
	 * @throws BizException
	 * @throws InterruptedException
	 * @throws TimeoutException
	 */
	public String retrieveFee(String chargerId) throws CreateConnectionFailException, RetryFailException, BizException, InterruptedException, TimeoutException
	{
		String message = "680000010000000001" + chargerId + "36" + serialGenerater.generateSerialNo14();

		MessageFuture future = longConnection.sendAsync(message, chargerId);

		if (future == null)
			throw new BizException("fail to retrieve fee from charger");

		if (future.await(Retrieve_Timeout * 1000))
		{
			String reply = future.getReplyMessage();
			if (future.isSuccess())
			{
				log.info("message returned successfully");
				return reply;
			}
			else
			{
				log.debug(future.getErrorCode() + " " + future.getErrorMessage());
				throw new BizException(future.getErrorCode(), future.getErrorMessage());
			}
		}
		else
		{
			log.debug("Time-out on retrieving fee, No respond from charger");
			throw new TimeoutException("No respond from charger");
		}

	}

}